# This is a sample Python script.
from time import sleep
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
import base64
import cv2
import matplotlib.pyplot as plt
import numpy as np

DIR_PATH = 'img1/'
TEST_DIR_PATH = 'img/'
 

def find_black_count(pixel):
    # 通过逼近的方式进行计算
    _nums = 0
    _x = 0
    is_interval = False
    if sum(pixel) != 0:
        _nums = sum(pixel) // 255
        x_index_list = np.where(pixel == 255)
        if len(x_index_list) > 0:
            _x = x_index_list[0][0]
        ones_indices = np.where(np.diff(np.concatenate(([0], pixel, [0]))) == 255)
        print(ones_indices[0])
        if len(ones_indices[0]) >= 2:
            is_interval = True

    return _nums, _x, is_interval


def compute_slider_image(thresh_image):
    """通过轮廓图填充实体"""
    # 查找轮廓
    contours, _ = cv2.findContours(thresh_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # 创建一个全黑的图像，用于绘制填充后的轮廓
    _image = np.copy(thresh_image)
    filled_image = np.zeros_like(_image)
    # 遍历轮廓并填充
    for contour in contours:
        # 填充轮廓
        cv2.drawContours(filled_image, [contour], -1, (255), thickness=cv2.FILLED)
    return filled_image


def compute_test_image(x, y, scroll_width, back_image_url, image_url):
    """
    :param x: 验证码x坐标
    :param y: 验证码图片相对背景图片y坐标
    :param scroll_width:  滚动条宽度
    :param back_image_url: 背景图片文件url
    :param image_url: 图片文件url
    :return: 当前移动的坐标
    """
    _pt_x = 0
    slider_pic = cv2.imread(image_url)
    back_image_pic = cv2.imread(back_image_url)
    # 拼接彩图
    image = cv2.imread(image_url, 0)
    # back_image = cv2.imread(back_image_url, 0)
    cut_image_shape = image.shape

    # 进行色彩转换
    slider_pic = cv2.cvtColor(slider_pic, cv2.COLOR_BGR2GRAY)
    _r, _th = cv2.threshold(slider_pic, 250, 255, cv2.THRESH_BINARY)
    _th = compute_slider_image(_th)

    back_image_pic = cv2.cvtColor(back_image_pic, cv2.COLOR_BGR2GRAY)
    _, thresh = cv2.threshold(back_image_pic, 220, 255, cv2.THRESH_BINARY)

    # 切割相应背景
    # 计算出当前的图片区间
    new_thresh = np.copy(thresh[y:y + cut_image_shape[0], 0:thresh.shape[1]])
    # 核心进行匹配
    res = cv2.matchTemplate(image=new_thresh, templ=_th, method=cv2.TM_CCOEFF_NORMED)
    # print(res)
    loc = np.where(res == np.max(res))
    # 可能匹配多个目标的固定写法，如果是确定只有一个目标可以用 minMaxLoc 函数处理，从loc中遍历得到的左上坐标 pt -> (10, 10)
    back_image = cv2.imread(back_image_url)
    back_image = np.copy(back_image[y:y + cut_image_shape[0], 0:thresh.shape[1]])

    for pt in zip(*loc[::-1]):
        # 指定左上和右下坐标 画矩形
        _pt_x = pt[0] + x
        cv2.rectangle(back_image, pt, (pt[0] + cut_image_shape[1], pt[1] + cut_image_shape[0]), color=(0, 0, 255),
                      thickness=2)
    plt.imshow(back_image)
    plt.show()
    # 进行边界判断和界限判断
    return _pt_x


if __name__ == '__main__':
    # 解析图片
    _x = 0
    _y = 47
    _scroll_width = 330

    # 给定x、y、宽、back_img、img1
    # compute_image_code(_x, _y, _scroll_width, './img1/back.png', './img1/cut.png')
    print(compute_test_image(_x, 45, _scroll_width, './img2/back.png', './img2/cut.png'))

    # 得到答案
    _left_width = 128
    # 网络请求的x、y
    _s_x = 132
    _s_y = 47
